C: build a library1
2gcc -c -fPIC libtest.c
gcc -shared libtest.o -o libtest.so
Python: load the library1
2
3from ctypes import *
libtest = cdll.LoadLibrary(libtest.so')
print libtest.func(arg_list)
Makefile sample and python sample code
c_void_p
For the types without need to know the detailed layout, we can just use c_void_p
, especially when we cannot find the strictly matched self-defined type such as LP_cfloat_1024
.
pointer, POINTER, byref
POINTER is used for defining type.
pointer and byref function similarly. However, pointer does a lot more work since it constructs a real pointer object, so it is faster to use byref if you don’t need the pointer object in Python itself.
memory issue:
write free function in C code1
2
3
4
5void freeme(char *ptr)
{
printf("freeing address: %p\n", ptr);
free(ptr);
}
call free function in Python1
2
3
4lib = cdll.LoadLibrary('./string.so')
lib.freeme.argtypes = c_void_p,
lib.freeme.restype = None
lib.freeme(ptr)